﻿using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Fall.HttpClient
{
    /// <summary>
    /// HttpClient添加默认的信息
    /// 传递Token等等
    /// </summary>
    public class HttpContextMiddleware:DelegatingHandler
    {
        private readonly IHttpContextAccessor httpContextAccessor;

        public HttpContextMiddleware(IHttpContextAccessor httpContextAccessor) 
        {
            this.httpContextAccessor = httpContextAccessor;
        }

        /// <summary>
        /// 发送请求之前
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            request.Headers.Add("requestMethod", httpContextAccessor.HttpContext.Request.Method);
            request.Headers.Add("requestPath", httpContextAccessor.HttpContext.Request.Path.Value);
            if(httpContextAccessor.HttpContext.Request.Headers.ContainsKey("BearToken"))
                request.Headers.Add("BearToken", httpContextAccessor.HttpContext.Request.Headers.FirstOrDefault(w => w.Key == "BearToken").Value.ToString());
            return base.SendAsync(request, cancellationToken);
        }
    }
}
